/**
 *
 */
package com.xidian.zhiancloud.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.syset.SysUser;

/**
 * @author zwt
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            SysUser user = (SysUser) request.getSession().getAttribute("user");
            if("OPTIONS".equals(request.getMethod().toUpperCase())) {
                return true;
            }
            if (user != null) {
                return true;
            }
            System.out.println("未登录，正在访问 " + request.getRequestURI());
            //response.sendRedirect(request.getContextPath()+"/login");
            // response.sendRedirect("/account/login");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            String userJson = JSON.toJSONString(ResultDTO.errorOf(GeneralResponseEnums.NOT_LOGIN));
            PrintWriter out = null;
            ResultDTO.errorOf(GeneralResponseEnums.NOT_LOGIN);
            out = response.getWriter();
            out.append(userJson);
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
    }


}
